#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：receiver.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/20 上午12:14 
"""

import logging
from typing import Callable, Any

from protocols.tcp_protocol import TCPProtocol
from protocols.udp_protocol import UDPProtocol
from protocols.websocket_protocol import WebSocketProtocol


class Receiver:
	def __init__(self, protocol: str, host: str, port: int, callback: Callable[[bytes], Any]):
		"""
		初始化接收器。

		:param protocol: 协议类型 ('tcp', 'udp', 'websocket')
		:param host: 监听地址
		:param port: 监听端口
		:param callback: 接收到数据后的回调函数
		"""
		self.host = host
		self.port = port
		self.callback = callback
		self.protocol = self._get_protocol(protocol)

	def _get_protocol(self, protocol: str):
		"""根据协议类型返回相应的协议实例"""
		if protocol == 'tcp':
			return TCPProtocol(self.host, self.port, self.callback)
		elif protocol == 'udp':
			return UDPProtocol(self.host, self.port, self.callback)
		elif protocol == 'websocket':
			return WebSocketProtocol(self.host, self.port, self.callback)
		else:
			raise ValueError(f"Unsupported protocol: {protocol}")

	def start(self):
		"""启动接收器"""
		try:
			self.protocol.start()
			logging.info(f"Receiver started on {self.host}:{self.port} using {self.protocol.__class__.__name__}")
		except Exception as e:
			logging.error(f"Failed to start receiver: {e}")
			raise

	def stop(self):
		"""停止接收器"""
		try:
			self.protocol.stop()
			logging.info("Receiver stopped.")
		except Exception as e:
			logging.error(f"Failed to stop receiver: {e}")
			raise
